<?php


namespace app\middleware;


use support\Redis;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class RedisLock implements MiddlewareInterface
{

    /**
     * 防止重复提交
     * @param Request $request
     * @param callable $handler
     * @return Response
     */
    public function process(Request $request, callable $handler): Response
    {
        $app = $request->app;
        if(in_array($app,['api'])){
            $user_id = $request->header('Access-Token');
        }else{
            $user_id = session('admin');
        }
        $controller = $request->controller;
        $data_c = explode('\\', $controller);
        if ($app) {
            $controller = $data_c[3];
        } else {
            $controller = $data_c[2];
        }
        if (in_array($controller, ['Login'])) {
            return $handler($request);
        }
        $action = $request->action;
        // 定义锁标识
        $key = $controller . '\\' . $action . $user_id;
        // 获取锁
        $is_lock = \app\service\RedisLock::get_lock($key, 10);
        if (empty($is_lock)) {
            return json(['code' => 1, 'msg' => '请求太频繁!']);
        }
        return $handler($request);
    }
}
